<template>
  <div>
    <el-dialog
      :title="props.title + titleDialog"
      @close="onClose"
      v-model="visible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="main">
        <el-scrollbar ref="scrollRef" :min-size="10">
          <div class="title">基本设置</div>
          <el-form
            :disabled="titleDialog === '详情'"
            :model="formParams"
            ref="formRef"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="活动名称" prop="name">
              <el-input
                v-model="formParams.name"
                placeholder="请输入活动名称，最多16字"
                maxlength="16"
                clearable
                input-style="width: 200px"
              />
              <div style="width: 100%">仅后台可看</div>
            </el-form-item>
            <el-form-item label="投放位置" prop="position">
              <div>{{ props.title }}</div>
            </el-form-item>
            <el-form-item :label="formParams.position === 3 ? '弹窗' : '轮播图'" prop="img">
              <div
                ><ImageUploadByType
                  v-model="formParams.img"
                  :isShowTip="false"
                  uploadType="1"
                  :limit="1"
                  :fileSize="10"
                  :imagePx="formParams.position === 5 ? [710, 236] : []"
                />
                {{ desc }}</div
              >
            </el-form-item>
            <el-form-item
              v-if="position !== 5"
              label="关联活动"
              prop="marketingId"
              :required="position === 3"
            >
              <div
                >{{ formParams.marketingName }}
                <el-button type="primary" plain @click="handleSelect" size="small">关联</el-button>
                <el-link
                  :disabled="titleDialog === '详情'"
                  v-show="formParams.marketingId"
                  type="info"
                  style="margin-left: 10px"
                  :underline="false"
                  @click="handleDelete"
                >
                  删除
                </el-link>
              </div>
            </el-form-item>
            <el-form-item
              label="跳转链接"
              prop="url"
              v-if="position !== 3 && formParams.marketingName"
            >
              <el-select
                v-model="formParams.url"
                filterable
                clearable
                fit-input-width
                placeholder="请选择"
              >
                <el-option
                  v-for="item in linkOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="position === 3"
              class="positionBox"
              label="参与点位"
              prop="positionType"
            >
              <el-radio-group
                @change="formParams.positionIds = null"
                v-model="formParams.positionType"
              >
                <div class="title2">普通点位</div>
                <el-radio :value="1" :label="1"> 全部 </el-radio>
                <el-radio :value="2" :label="2">
                  指定点位
                  <el-select
                    v-show="formParams.positionType === 2"
                    style="width: 240px"
                    v-model="formParams.positionIds"
                    multiple
                    filterable
                    clearable
                    fit-input-width
                    collapse-tags
                    collapse-tags-tooltip
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in positionOptions"
                      :key="item.positionId"
                      :label="item.positonName"
                      :value="item.positionId"
                    />
                  </el-select>
                </el-radio>
                <span style="margin-right: 100px"></span>

                <div class="title2">特殊点位</div>

                <el-radio :value="3" :label="3"> 全部 </el-radio>
                <el-radio :value="4" :label="4">
                  指定点位
                  <el-select
                    v-show="formParams.positionType === 4"
                    style="width: 240px"
                    v-model="formParams.positionIds"
                    multiple
                    filterable
                    clearable
                    fit-input-width
                    collapse-tags
                    collapse-tags-tooltip
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in specialPositionTypeOptions"
                      :key="item.positionId"
                      :label="item.positonName"
                      :value="item.positionId"
                    />
                  </el-select>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- <el-form-item v-if="position === 3" label="参与点位" prop="positionType">
              <el-radio-group v-model="formParams.positionType">
                <el-radio :value="0" :label="0" size="large"> 全部点位 </el-radio>
                <br />
                <el-radio :value="1" :label="1" size="large">
                  指定点位
                  <el-select
                    :disabled="formParams.positionType === 0"
                    style="width: 240px"
                    v-model="formParams.positionIds"
                    multiple
                    filterable
                    clearable
                    fit-input-width
                    collapse-tags
                    collapse-tags-tooltip
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in positionOptions"
                      :key="item.positionId"
                      :label="item.positonName"
                      :value="item.positionId"
                    />
                  </el-select>
                </el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item label="备注" prop="remark">
              <div style="width: 100%">
                <el-input
                  v-model="formParams.remark"
                  style="width: 300px"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  type="textarea"
                  maxlength="1000"
                  placeholder="请输入内容"
                  show-word-limit
                />
              </div>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
        <el-button @click="handleAction(false)">取消</el-button>
      </template>
    </el-dialog>
    <listDialog ref="listRef" @select="changeSelect" />
  </div>
</template>

<script setup>
import listDialog from './listDialog.vue'
import { addMiniBannerApi, updateMiniBannerApi, getMiniBannerDetailApi } from '@/api/advert'
import { listDataApi } from '@/api/system/dict/data'
import { getPositionListApi } from '@/api/marketing/activity'
const emit = defineEmits(['referesh'])
const listRef = ref(null)
const props = defineProps({
  title: {
    type: String,
    default: ''
  }
})

const position = ref('')
const desc = ref('')
const positionOptions = ref([]) // 普通点位
const specialPositionTypeOptions = ref([]) // 特殊点位
const scrollRef = ref(null)
const formRef = ref(null)
const submit = ref(false)
const titleDialog = ref('设置')
const visible = ref(false)
const linkOptions = ref([])

const formParams = reactive({
  id: '',
  position: '',
  img: '',
  url: '',
  marketingId: '',
  remark: '',
  name: '',
  marketingName: '',
  positionIds: null,
  positionType: 0
})

const checkId = (rule, value, callback) => {
  if (formParams.position === 3 && !formParams.marketingId) {
    callback(new Error('请选择关联活动'))
  } else {
    callback()
  }
}
function getPositions() {
  if (position.value !== 3) return
  getPositionListApi({ cityName: formParams.cityName }).then((res) => {
    positionOptions.value = res?.data?.filter((i) => i?.label === 2)
    specialPositionTypeOptions.value = res?.data?.filter((i) => i?.label === 1)
  })
}

const rules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  img: [{ required: true, message: '请上传图片', trigger: 'change' }],
  marketingId: [{ validator: checkId, message: '请选择关联活动', trigger: 'change' }],
  type: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  positionType: [{ required: true, validator: checkPosition, trigger: 'change' }]
}

function checkPosition(rule, value, callback) {
  console.log(value)
  if (value === 1 || value === 3) {
    callback()
  } else if (value === 2 || value === 4) {
    if (!formParams.positionIds || !formParams.positionIds.length) {
      callback(new Error('请选择点位'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请选择'))
  }
}

function getDataList() {
  listDataApi({ dictType: 'mini_ad_link' }).then((res) => {
    linkOptions.value = res?.rows.map((i) => {
      return {
        label: i.dictLabel,
        value: i.dictValue
      }
    })
  })
}

function onClose() {
  formRef.value.resetFields()
  formParams.marketingName = ''
  formParams.marketingId = ''
  formParams.img = ''
  formParams.name = ''
  formParams.positionType = 0
  formParams.positionIds = null
  formParams.remark = ''

  visible.value = false
}

function handleSelect() {
  listRef.value.init(formParams.marketingId, formParams.position, formParams.cityName)
}

function handleDelete() {
  formParams.marketingId = ''
  formParams.marketingName = ''
}

function changeSelect(item) {
  formParams.marketingId = item.id
  formParams.marketingName = item.name
}

function handleAction(confirm) {
  if (confirm) {
    submit.value = true
    formRef.value?.validate((valid) => {
      if (valid) {
        const params = { ...formParams }
        params.img = params.img?.length ? params.img[0].url : ''
        params.url = params.marketingName ? params.url : ''
        console.log('handleAction', params)
        if (formParams.id) {
          updateMiniBannerApi(params)
            .then(() => {
              submit.value = false
              onClose()
              emit('refresh')
              ElMessage({
                message: '活动修改成功',
                type: 'success'
              })
            })
            .catch(() => {
              submit.value = false
            })
          return
        }
        addMiniBannerApi(params)
          .then(() => {
            submit.value = false
            onClose()
            emit('refresh')
            ElMessage({
              message: '活动新建成功',
              type: 'success'
            })
          })
          .catch(() => {
            submit.value = false
          })
      } else {
        ElMessage({
          message: '提交失败，请校验数据',
          type: 'error'
        })
        submit.value = false
      }
    })
  } else {
    onClose()
  }
}

function getDetail(id) {
  getMiniBannerDetailApi(id).then((res) => {
    Object.keys(formParams).forEach((key) => {
      formParams[key] = res?.data[key]
    })
    formParams.img = res.data.img
      ? [
          {
            url: res.data.img
          }
        ]
      : ''
    visible.value = true
  })
}

async function init(row, type, text) {
  // console.log(row, type, text)
  position.value = row.position
  desc.value = text || row.desc
  formParams.position = row.position
  formParams.cityName = row.cityName
  titleDialog.value = type
  await Promise.all([getPositions(), getDataList()])
  if (type !== '新增') {
    formParams.id = row.id
    getDetail(row.id)
  } else {
    formParams.id = ''
    visible.value = true
  }
}

function referesh() {}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  transform: translate3d(0, -20px, 0);
  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
  }
  .textarea-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .textarea-info {
    line-height: 18px;
  }
  .upload-wrapper {
    display: flex;
    align-items: start;
  }
  .el-checkbox.el-checkbox--large {
    height: 32px;
  }
}
.el-radio-group .el-radio {
  width: 100%;
}
::v-deep .el-upload-list__item {
  transition: none !important;
}

.positionBox {
  .title2 {
    font-size: 14px;
    font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
      Arial, sans-serif;
  }
  .el-radio-group .el-radio {
    width: auto;
  }
  .el-radio-group {
    display: block;
  }
}
</style>
